package controller

import (
	"danmu/common"
	"danmu/dto"
	"danmu/model"
	"danmu/response"
	"danmu/util"
	"log"
	"net/http"
	"strconv"

	"golang.org/x/crypto/bcrypt"

	"github.com/gin-gonic/gin"
)

func AdminLogin(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	var requestUser = model.Admin{}
	err := ctx.Bind(&requestUser)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	password := requestUser.Password
	email := requestUser.Email
	//数据验证
	if !util.VerifyEmailFormat(email) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "邮箱格式有误")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不能少于六位")
		return
	}
	//判断邮箱是否存在
	var admin model.Admin
	DB.Where("email = ?", email).First(&admin)
	if admin.ID == 0 {
		//判断是否为第一个注册的用户
		var user model.User
		DB.Where("email = ?", email).First(&user)
		if user.ID == 1{
			//判断密码
			if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
				response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码错误")
				return
			}
			//添加管理员
			var newAdmin = model.Admin{
				Uid:user.ID,
				Name:user.Name,
				Email:user.Email,
				Password:user.Password,
			}
			//添加管理员
			DB.Create(&newAdmin)
			//修改用户信息
			DB.Where("id = ?", newAdmin.Uid).Model(model.User{}).Update("is_admin", 1)
			response.Fail(ctx,nil,"请重新登录")
		}else {
			response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
			return
		}
	}
	//判断密码
	if err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(password)); err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码错误")
		return
	}
	//根据adminId查询用户信息
	var user = model.User{}
	//查询用户信息
	DB.First(&user, admin.Uid)
	//发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusUnprocessableEntity, 500, nil, "系统异常")
		log.Printf("token generate error", err)
		return
	}
	//返回数据
	response.Success(ctx, gin.H{"token": token, "data": user, "id": admin.ID}, "登陆成功")
}

func AddAdmin(ctx *gin.Context) {
	DB := common.GetDB()
	var requestUser = model.User{}
	var newAdmin = model.Admin{}
	var userInfo = model.User{}
	err := ctx.Bind(&requestUser)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestUser.ID
	//查询用户信息
	DB.First(&userInfo, id)
	//如果管理员存在，则返回已存在
	DB.Where("email = ?", userInfo.Email).First(&newAdmin)
	if newAdmin.ID != 0 {
		response.Fail(ctx, nil, "管理员已存在")
		return
	}

	newAdmin.Uid = userInfo.ID
	newAdmin.Name = userInfo.Name
	newAdmin.Email = userInfo.Email
	newAdmin.Password = userInfo.Password
	//添加管理员
	DB.Create(&newAdmin)
	//修改用户信息
	DB.Where("id = ?", newAdmin.Uid).Model(model.User{}).Update("is_admin", 1)
	response.Success(ctx, nil, "添加成功")
}

func DeleteAdmin(ctx *gin.Context)  {
	DB := common.GetDB()
	var requestUser = model.User{}
	var userInfo = model.User{}
	var newAdmin = model.Admin{}
	err := ctx.Bind(&requestUser)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestUser.ID
	//查询用户信息
	DB.First(&userInfo, id)
	//如果管理员存在，则返回已存在
	DB.Where("email = ?", userInfo.Email).First(&newAdmin)
	if newAdmin.ID != 0 {
		DB.Delete(&newAdmin)
		DB.Where("id = ?", newAdmin.Uid).Model(model.User{}).Update("is_admin", 0)
		response.Success(ctx, nil, "移除成功")
	}else{
		response.Fail(ctx, nil, "管理员不存在")
	}
}

func UserList(ctx *gin.Context) {
	DB := common.GetDB()
	var users []model.User
	//获取分页信息
	page, _ := strconv.Atoi(ctx.Query("page"))
	pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
	if page > 0 && pageSize > 0 {
		//记录总数
		var totalSize int
		DB = DB.Limit(pageSize).Offset((page - 1) * pageSize)
		//评论
		DB.Find(&users).Count(&totalSize)
		response.Success(ctx, gin.H{"count": totalSize, "data": dto.ToUserListDto(users)}, "获取成功")
	}
}

func ModifyUserInfo(ctx *gin.Context) {
	DB := common.GetDB()
	var user model.User
	//获取参数
	var requestUser = model.User{}
	err := ctx.Bind(&requestUser)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestUser.ID
	email := requestUser.Email
	name := requestUser.Name
	sign := requestUser.Sign
	if len(name) == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "名称不能为空")
		return
	}
	if !util.VerifyEmailFormat(email) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "邮箱格式有误")
		return
	}
	//根据id查找用户
	DB.First(&user, id)
	DB.Model(&user).Updates(model.User{Email: email, Name: name, Sign: sign})
	response.Success(ctx, nil, "修改成功")
}

func DeleteUser(ctx *gin.Context) {
	DB := common.GetDB()
	var requestUser = model.User{}
	var user = model.User{}
	err := ctx.Bind(&requestUser)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestUser.ID
	//查询用户信息
	DB.First(&user, id)
	if user.ID == 0 {
		response.Fail(ctx, nil, "用户不存在")
		return
	}
	DB.Delete(&user)
	response.Success(ctx, nil, "删除成功")
}

func VideoInfoList(ctx *gin.Context) {
	DB := common.GetDB()
	var video []model.Video
	//获取分页信息
	page, _ := strconv.Atoi(ctx.Query("page"))
	pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
	if page > 0 && pageSize > 0 {
		//记录总数
		var totalSize int
		DB = DB.Limit(pageSize).Offset((page - 1) * pageSize)
		//评论
		DB.Find(&video).Count(&totalSize)
		response.Success(ctx, gin.H{"count": totalSize, "data": dto.ToVideoInfoDto(video)}, "获取成功")
	}
}

func ModifyVideoInfo(ctx *gin.Context) {
	DB := common.GetDB()
	var video model.Video
	//获取参数
	var requestVideo = model.Video{}
	err := ctx.Bind(&requestVideo)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestVideo.ID
	title := requestVideo.Title
	content := requestVideo.Content
	show := requestVideo.IsShow

	if len(title) == 0 || len(title) == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "数据有误")
		return
	}
	DB.First(&video, id)
	DB.Debug().Model(&video).Updates(model.Video{Title: title, Content: content}).Update("is_show", show)
	response.Success(ctx, nil, "修改成功")
}

func AdminDeleteVideo(ctx *gin.Context) {
	DB := common.GetDB()
	var requestVideo = model.Video{}
	var video = model.Video{}
	err := ctx.Bind(&requestVideo)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestVideo.ID
	//查询用户信息
	DB.First(&video, id)
	if video.ID == 0 {
		response.Fail(ctx, nil, "视频不存在")
		return
	}
	DB.Delete(&video)
	response.Success(ctx, nil, "删除成功")
}

func AddAnnounce(ctx *gin.Context) {
	DB := common.GetDB()
	var announce = model.Announce{}
	err := ctx.Bind(&announce)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	title := announce.Title
	content := announce.Content
	url := announce.Url
	newAnnounce := model.Announce{
		Title:   title,
		Content: content,
		Url:     url,
	}
	DB.Create(&newAnnounce)
	//返回结果
	response.Success(ctx, nil, "发送成功")
}

func DeleteAnnounce(ctx *gin.Context) {
	DB := common.GetDB()
	var announce = model.Announce{}
	var ann = model.Announce{}
	err := ctx.Bind(&announce)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := announce.ID

	//查询通知信息
	DB.First(&ann, id)
	if ann.ID == 0 {
		response.Fail(ctx, nil, "通知不存在")
		return
	}
	DB.Delete(&ann)
	//删除用户拉取的通知
	DB.Where("aid = ?", ann.ID).Delete(model.AnnounceUser{})
	response.Success(ctx, nil, "删除成功")
}

func AnnounceList(ctx *gin.Context) {
	DB := common.GetDB()
	var announces []model.Announce
	//获取分页信息
	page, _ := strconv.Atoi(ctx.Query("page"))
	pageSize, _ := strconv.Atoi(ctx.Query("page_size"))
	if page > 0 && pageSize > 0 {
		//记录总数
		var totalSize int
		DB = DB.Limit(pageSize).Offset((page - 1) * pageSize)
		//评论
		DB.Find(&announces).Count(&totalSize)
		response.Success(ctx, gin.H{"count": totalSize, "data": dto.ToAnnounceListDto(announces)}, "获取成功")
	}
}

func UploadCarouselInfo(ctx *gin.Context) {
	DB := common.GetDB()
	//从参数中获取标题和简介
	var requestCarousel = model.Carousel{}
	err := ctx.Bind(&requestCarousel)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	title := requestCarousel.Title
	imgName := requestCarousel.Img
	url := requestCarousel.Url
	//验证数据
	if len(title) == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "标题不能为空")
		return
	}
	if len(imgName) == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "图片不存在")
		return
	}

	newCarousel := model.Carousel{
		Title:     title,
		Img: imgName,
		Url: url,
	}
	DB.Create(&newCarousel)
	response.Success(ctx, nil, "上传成功")
}

func DeleteCarouse(ctx *gin.Context)  {
	DB := common.GetDB()
	//从参数中获取标题和简介
	var requestCarousel = model.Carousel{}
	err := ctx.Bind(&requestCarousel)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "请求错误")
		return
	}
	id := requestCarousel.ID
	var carousel model.Carousel
	DB.First(&carousel, id)
	if carousel.ID == 0 {
		response.Fail(ctx, nil, "轮播图不存在")
		return
	}
	DB.Delete(&carousel)
	response.Success(ctx, nil, "删除成功")
}